import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.swing.*;

public class ShareMenuItemListener implements ActionListener{

	private String text;
	private MultiDraw2 md;
	
	ShareMenuItemListener(MultiDraw2 md, String text){
		this.text = text;
		this.md = md;
	}

	public void actionPerformed(ActionEvent e) {
//---------------------------------------------------
		if(text.equals("shareTool")){
			//get tool file
			boolean anyNullFiles = false;
			File tFi = getFile("Tool.class");
			ToolKit tk = new ToolKit(tFi.getName().replace("Tool.class", ""));
			System.out.println(tk.getName());
			byte[] t = getBytes(tFi);
			System.out.println(t.length);
			if(t !=null){
				tk.setToolFi(t);
			}else{anyNullFiles = true;}
			//get object file
			File oFi = getFile(tk.getName()+"Object.class");
			byte[] o = getBytes(oFi);
			
			System.out.println(tk.getName()+"Object.class "+o.length);
			if(t !=null){
				tk.setObjectFi(o);
			}else{anyNullFiles = true;}
			//get image file
			File iFi = getFile(tk.getName().substring(1)+".jpg");
			byte[] i = getBytes(iFi);
			System.out.println(".jpg "+i.length);
			if(t !=null){
				tk.setImageFi(i);
			}else{anyNullFiles = true;}
			if(!anyNullFiles){
				md.mdUser.rt.toolKit = tk;
				md.mdUser.remoteOut.println("<<UPLOADNEWTOOLKIT>>"+tk.getName());
				System.out.println("ready to upload toolkit "+tk.getName());
			}
			//show error message to user
		}
//---------------------------------------------------------------------------------
	}
	protected File getFile(String sfx){
		JFileChooser chooser = new JFileChooser();
		String[] ext = new String[1];
		ext[0] = sfx;
		FNameSuffixFilter fnsf = new FNameSuffixFilter(sfx,ext);
		chooser.addChoosableFileFilter(fnsf);
		chooser.showOpenDialog(md);
		return chooser.getSelectedFile();
	}
	protected byte[] getBytes(File f){
		byte[] b = new byte[(int) f.length()];
		FileInputStream fis;
		try {
			fis = new FileInputStream(f);
		
		    int i = fis.read(b);
		    fis.close();
		} catch (FileNotFoundException e1) {e1.printStackTrace(); return null;
		} catch (IOException ioe) {ioe.printStackTrace(); return null;
		}
		return b;
	}
}
